import store from "../store";
import storage from "../utils/storage";
import { createRouter, createWebHistory } from "vue-router";

import basic from "./z-basic";
import routes from "./routes";

export const router = createRouter({
	history: createWebHistory(),
	routes: [
		{
			path: "/login",
			name: "Login",
			component: () => import("@/views/Login.vue"),
		},
		{
			path: '/',
			name: 'Main',
			component: () => import("@/views/Main.vue"),
			redirect: '/home',
			children: [
				...basic,
				...routes
			]
		},

		//这个*匹配必须放在最后，将改路由配置放到所有路由的配置信息的最后，否则会其他路由path匹配造成影响。
		{ path: "/:pathMatch(.*)", redirect: "/" },
	],
});
const whiteList = ["/login"]; // 白名单

async function beforePushHandler(to) {
	if (!storage.getVoucher() && whiteList.indexOf(to.path) === -1) {
		return "/login";
	}
	const curentPath = store.state.user.path;
	// 跳转登录时记录上一个页面的路由，登陆之后跳转回去
	if (to.path === '/login' && !to.query['back'] && curentPath) {
		const lastUrl = curentPath.startsWith('/login') ? '/' : curentPath;
		const backEncode = encodeURIComponent(lastUrl);
		return `/login?back=${backEncode}`
	}
	return null;
}

router.beforeEach(async (to, from, next) => {
	const route = await beforePushHandler(to);
	store.state.user.path = to.fullPath;
	if (route) return next(route);
	if (to.meta['title']) document.title = to.meta.title
	next();
});

export default router